package com.usian.Controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.usian.UserFeign;
import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Value("${config.info}")
    private String configInfo;
    @RequestMapping("/findById/{id}")
    public User findById(@PathVariable Integer id){
        //通过服务获取示例 serviceId = 要调用的微服务的服务名(yml spring.application.name="provider")
        ServiceInstance instance = loadBalancerClient.choose("provider");
        //拼接请求路径  http://localhost:9090/findById/8
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/findById/"+id;
        User user = restTemplate.getForObject(url, User.class);
        System.out.println("========:"+configInfo);
        return user;
    }



    //使用feign做远程调用
    @Autowired
    private UserFeign userFeign;
    @RequestMapping("/findByIds/{id}")
    @SentinelResource(value = "findByIds",blockHandler = "blockTest",fallback = "fallTest")
    public User findByIds(@PathVariable Integer id){
//        int a=100/0;
        User user = userFeign.findById(id);
        return user;
    }
    public User blockTest(@PathVariable Integer id, BlockException e){
        return new User(1,"我是熔断后block的托底数据",3);
    }
    public User fallTest(@PathVariable Integer id, Throwable e){
        return new User(1,"fall托底数据",3);
    }
    @GetMapping("/findByName")
    public User findByName(Integer id,String name){
        return userFeign.findByName(id,name);
    }
    @PostMapping("/findByUser")
    public User findByUser(@RequestBody User user){
       return userFeign.findByUser(user);
    }


}
